<template>
  <div class="product-container">
    <a-card>
      <!-- 搜索区域 -->
      <div class="search-wrapper">
        <a-form layout="inline" :model="searchForm">
          <div class="search-row">
            <a-form-item label="商品名称">
              <a-input v-model:value="searchForm.name" placeholder="请输入商品名称" />
            </a-form-item>
            <!-- 农户ID搜索框，仅管理员可见 -->
            <a-form-item label="农户ID" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
              <a-input v-model:value="searchForm.farmerId" placeholder="请输入农户ID" />
            </a-form-item>
            <!-- 农户名称搜索框，仅管理员可见 -->
            <a-form-item label="农户名称" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
              <a-input v-model:value="searchForm.farmName" placeholder="请输入农户名称" />
            </a-form-item>
            <a-form-item label="商品分类">
              <a-select
                v-model:value="searchForm.categoryId"
                placeholder="请选择分类"
                style="width: 160px"
                allowClear
              >
                <a-select-option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="search-buttons">
              <a-space>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button @click="handleReset">重置</a-button>
              </a-space>
            </a-form-item>
            <!-- 操作按钮 -->
            <div style="margin-bottom: 16px">
              <a-button v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER" type="primary" @click="handleAdd">新增商品</a-button>
            </div>
          </div>
        </a-form>
      </div>

      <!-- 标签页 -->
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange" class="product-tabs">
        <a-tab-pane key="all" tab="全部商品" />
        <a-tab-pane key="active" tab="已上架" />
        <a-tab-pane key="inactive" tab="已下架" />
      </a-tabs>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="productList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total: number) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <img :src="record.image" alt="商品图片" class="product-image" />
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'success' : 'default'">
              {{ record.status === 'active' ? '已上架' : '已下架' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'price'">
            ¥{{ record.price?.toFixed(2) }}
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleDetail(record)">查看详情</a-button>
              <!-- 仅农户可以编辑、上下架、删除 -->
              <template v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER">
                <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                <a-button
                  type="link"
                  @click="handleToggleStatus(record)"
                  :danger="record.status === 'active'"
                >
                  {{ record.status === 'active' ? '下架' : '上架' }}
                </a-button>
                <a-popconfirm
                  title="确定要删除这个商品吗？"
                  @confirm="handleDelete(record)"
                >
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑商品弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="800px"
      @ok="handleModalOk"
    >
      <a-form
        :model="productForm"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="商品名称" name="name">
          <a-input v-model:value="productForm.name" />
        </a-form-item>
        <a-form-item label="商品分类" name="categoryId">
          <a-select v-model:value="productForm.categoryId">
            <a-select-option v-for="item in categories" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="商品图片" name="image">
          <upload-image
            v-model:value="productForm.image"
            :biz="BIZ_TYPE.PRODUCT_IMG"
          />
        </a-form-item>
        <a-form-item label="商品描述" name="description">
          <a-textarea
            v-model:value="productForm.description"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 图片预览 -->
    <a-modal
      v-model:visible="previewVisible"
      title="图片预览"
      :footer="null"
    >
      <img alt="预览" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  listProductVoByPageUsingPost,
  listProductVoByPageForPcUsingPost,
  addProductUsingPost,
  updateProductUsingPost,
  deleteProductUsingPost
} from '@/api/productController';
import { listCategoryByPageUsingPost, listCategoryVoByPageUsingPost } from '@/api/categoryController';
import { getFarmersVoByUserIdUsingGet } from '@/api/farmersController';
import UploadImage from '@/components/UploadImage.vue';
import { BIZ_TYPE } from '@/constants/upload';
import { PRODUCT_STATUS, PRODUCT_STATUS_TEXT } from '@/constants/product';
import { USER_ROLE } from '@/constants/user';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';
import { formatDateTime } from '@/utils/format';

const router = useRouter();
const userStore = useUserStore();

// 当前标签页
const activeTab = ref('all');

// 搜索表单
const searchForm = ref({
  name: undefined,
  categoryId: undefined,
  farmerId: undefined,
  farmName: undefined,
  status: undefined,
  current: 1,
  pageSize: 10,
  sortField: 'createTime' as string | undefined,
  sortOrder: 'descend' as string | undefined
});

// 表格列定义
const columns = [
  {
    title: '商品图片',
    key: 'image',
    width: 100
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  /*{
    title: '商品分类',
    dataIndex: ['category', 'name'],
    key: 'category',
    width: 120
  },*/
  {
    title: '销量',
    dataIndex: 'sales',
    key: 'sales',
    width: 100,
    sorter: true
  },
  {
    title: '最低价格',
    dataIndex: 'minPrice',
    key: 'minPrice',
    width: 100
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 表格数据
const productList = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 分类数据
const categories = ref([]);

// 获取农户ID
const getFarmerId = async () => {
  if (userStore.userInfo?.userRole === USER_ROLE.FARMER && userStore.userInfo?.id) {
    try {
      const res = await getFarmersVoByUserIdUsingGet({
        userId: userStore.userInfo.id
      });
      if (res.data?.id) {
        searchForm.value.farmerId = res.data.id;
      }
    } catch (error) {
      console.error('获取农户信息失败', error);
    }
  }
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await listCategoryVoByPageUsingPost({
      current: 1,
      pageSize: 40
    });
    categories.value = res.data?.records || [];
  } catch (error) {
    // 移除错误处理，由拦截器统一处理
  }
};

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true;
  try {
    // 构建请求参数，不携带空排序参数
    const requestParams: any = {
      ...searchForm.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      status: activeTab.value === 'all' ? undefined : activeTab.value
    };
    
    // 当排序字段为空时，不传递排序相关参数
    if (!requestParams.sortField) {
      delete requestParams.sortField;
      delete requestParams.sortOrder;
    }
    
    const res = await listProductVoByPageForPcUsingPost(requestParams);
    productList.value = res.data?.records || [];
    pagination.value.total = res.data?.total || 0;
  } catch (error) {
    // 错误处理由拦截器统一处理
  } finally {
    loading.value = false;
  }
};

// 标签页切换
const handleTabChange = () => {
  pagination.value.current = 1;
  fetchProductList();
};

// 表格变化
const handleTableChange = (pag: {current: number, pageSize: number}, filters: any, sorter: any) => {
  // 更新分页参数
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  
  // 更新排序参数
  if (sorter && sorter.order) {
    searchForm.value.sortField = sorter.field;
    searchForm.value.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
  } else {
    // 无排序时，设置为空字符串
    searchForm.value.sortField = '';
    searchForm.value.sortOrder = '';
  }

  fetchProductList();
};

// 搜索
const handleSearch = () => {
  pagination.value.current = 1;
  fetchProductList();
};

// 重置
const handleReset = () => {
  // 重置时，如果是农户，保留farmerId
  const farmerId = userStore.userInfo?.userRole === USER_ROLE.FARMER ? searchForm.value.farmerId : undefined;
  
  searchForm.value = {
    name: undefined,
    categoryId: undefined,
    farmerId: farmerId,
    farmName: undefined,
    status: undefined,
    current: 1,
    pageSize: 10,
    sortField: 'createTime',
    sortOrder: 'descend'
  };
  
  pagination.value.current = 1;
  pagination.value.pageSize = 10;
  
  fetchProductList();
};

// 商品表单
const modalVisible = ref(false);
const modalTitle = ref('');
const productForm = ref<API.ProductAddRequest | API.ProductUpdateRequest>({
  id: undefined,
  name: '',
  categoryId: undefined,
  image: '',
  description: '',
  status: PRODUCT_STATUS.ACTIVE  // 使用常量
});

// 图片上传相关
const fileList = ref<any[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');

const beforeUpload = (file: File) => {
  return false; // 阻止自动上传
};

const handlePreview = async (file: any) => {
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
};

// 新增商品
const handleAdd = () => {
  modalTitle.value = '新增商品';
  productForm.value = {
    id: undefined,
    name: '',
    categoryId: undefined,
    image: '',
    description: '',
    status: PRODUCT_STATUS.ACTIVE  // 使用常量
  };
  fileList.value = [];
  modalVisible.value = true;
};

// 编辑商品
const handleEdit = (record: any) => {
  modalTitle.value = '编辑商品';
  productForm.value = { ...record };
  fileList.value = record.image ? [{
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: record.image,
  }] : [];
  modalVisible.value = true;
};

// 保存商品
const handleModalOk = async () => {
  try {
    const api = productForm.value?.id ? updateProductUsingPost : addProductUsingPost;
    const res = await api(productForm.value);
    message.success(`${modalTitle.value}成功`);
    modalVisible.value = false;
    await fetchProductList();
  } catch (error) {
    // 移除这里的错误提示
  }
};

// 切换商品状态
const handleToggleStatus = async (record: any) => {
  try {
    await updateProductUsingPost({
      id: record.id,
      status: record.status === PRODUCT_STATUS.ACTIVE ? PRODUCT_STATUS.INACTIVE : PRODUCT_STATUS.ACTIVE,
      name: record.name,
      categoryId: record.categoryId,
      description: record.description,
      image: record.image
    });
    message.success('操作成功');
    await fetchProductList();
  } catch (error) {
    // 移除错误处理，由拦截器统一处理
  }
};

// 删除商品
const handleDelete = async (record: any) => {
  try {
    const res = await deleteProductUsingPost({
      id: record.id
    });
    if (res.data === true) {
      message.success('删除成功');
      await fetchProductList();
    }
  } catch (error) {
    // 移除错误处理，由拦截器统一处理
  }
};

// 查看详情
const handleDetail = (record: any) => {
  router.push(`/products/${record.id}`);
}

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入商品名称' }],
  categoryId: [{ required: true, message: '请选择商品分类' }]
}

onMounted(async () => {
  // 如果是农户用户，先获取farmerId
  await getFarmerId();
  fetchCategories();
  fetchProductList();
});
</script>

<style scoped>
.product-container {
  padding: 24px;
  background: #f0f2f5;
}

.search-wrapper {
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-buttons {
  margin-left: auto;
  margin-right: 0;
}

.product-tabs {
  margin-bottom: 16px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

:deep(.ant-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.ant-form-item-label) {
  min-width: 80px;
}
</style>
